import { createRouter, createWebHistory } from 'vue-router'
import routes from './routes'
import { useUserInfoStore } from '@/stores/user'
import { readToken, removeToken } from '../utils/auth'

const router = createRouter({
  history: createWebHistory(),
  routes,
  scrollBehavior(to, from, savePosition) {
    if (savePosition) {
      return savePosition
    } else {
      return { x: 0, y: 0 }
    }
  },
})

router.beforeEach(async (to, from, next) => {
  const token = readToken()
  if (token) {
    const userStore = useUserInfoStore()
    if (userStore.userInfo.id) {
      next()
    } else {
      try {
        await userStore.getUserInfo()
        next()
      } catch (error) {
        removeToken()
        next(`/login?redirect=${to.fullPath}`)
      }
    }
  } else {
    const pathArr = ['/trade', '/pay', '/paysuccess', '/center']
    if (pathArr.includes(to.path)) {
      next(`/login?redirect=${to.fullPath}`)
    } else {
      next()
    }
  }
})

export default router
